package org.mm4juser.config;

import org.mm4juser.intercepter.TokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.FileSystems;

@Configuration
public class WebConfig implements WebMvcConfigurer {
	private static final String BASE_PATH = "file:" + System.getProperty("user.dir");
	
	@Bean
	public TokenInterceptor tokenInterceptor() {
		return new TokenInterceptor();
	}
	
	/**
	 * 拦截器配置
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(tokenInterceptor())
			.addPathPatterns("/ul/**")
			.addPathPatterns("/iu/**")
			.addPathPatterns("/ua/**")
			.excludePathPatterns("/ul/login")
			.order(2);
	}
	
	/**
	 * 跨域资源请求配置
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**") // 允许所有路径
			.allowedOrigins("http://localhost:5173") // 允许所有前端域名
			.allowedMethods(
				"GET",
				"POST",
				"PUT",
				"DELETE",
				"OPTIONS") // 允许的HTTP方法
			.allowedHeaders("*") // 允许所有请求头
			.exposedHeaders(
				"Access-Control-Allow-Origin",
				"Access-Control-Allow-Credentials") // 暴露的响应头
			.allowCredentials(true) // 允许前端携带Cookie（关键配置）
			.maxAge(3600); // 预检请求缓存时间（秒）
	}
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 用户头像静态资源
		registry.addResourceHandler("/img/**")
			.addResourceLocations(
				BASE_PATH + FileSystems.getDefault()
					.getSeparator() + "data" + FileSystems.getDefault()
					.getSeparator() + "img" + FileSystems.getDefault()
					.getSeparator() + "userAvatar");
	}
}
